package com.jijs.framework.controller.admin;

import java.io.File;
import java.io.IOException;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.fasterxml.jackson.core.JsonGenerationException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jijs.framework.CodeConstant;
import com.jijs.framework.controller.BaseController;
import com.jijs.framework.model.EasyUIComboTree;
import com.jijs.framework.model.EasyUIDataGrid;
import com.jijs.framework.model.JsonResult;
import com.jijs.framework.model.PageHelper;
import com.jijs.framework.model.pmodel.AdeUser;
import com.jijs.framework.service.ModuleManagerService;
import com.jijs.framework.service.RoleManagerService;
import com.jijs.framework.service.UserManagerService;
import com.jijs.framework.util.CaptchaUtil;
import com.jijs.framework.util.JacksonUtil;
import com.jijs.framework.util.LogUtil;
import com.jijs.framework.util.StringUtil;
import com.jijs.framework.util.UserUtil;

/**
 * 用户控制器
 * 
 * @author jijs
 * 
 */
@Controller
@RequestMapping("/admin/userManager")
public class UserManagerController extends BaseController {

    @Autowired
    private UserManagerService userService;

    @Autowired
    private RoleManagerService roleService;

    @Autowired
    private ModuleManagerService moduleService;

    @Value("${adminLoginCaptcha}")
    private boolean adminLoginCaptcha = false;

    /**
     * 用户登录操作
     * 
     * @param user
     *            用户信息
     * @param request
     *            请求信息
     * @return
     */
    @ResponseBody
    @RequestMapping("/login")
    public JsonResult login(AdeUser user, HttpServletRequest request) {

        // 返回结果
        JsonResult j = new JsonResult();

        if (adminLoginCaptcha) {
            String message = CaptchaUtil.isValidate(user.getCaptcha(), request.getSession());

            if (message != null) {
                j.setMsg(message + "，请重新输入验证码！");
                return j;
            }
        }

        AdeUser u = userService.login(user);
        if (u != null) {

            if (CodeConstant.STATE_FREEZE.equals(u.getUserState())) {
                j.setSuccess(false);
                j.setMsg("用户已经被停用，无法登录，请联系管理员！");
            } else {
                u.setModuleList(userService.moduleList(user));

                UserUtil.setLoginUser(request, user);

                j.setSuccess(true);
                j.setMsg("登陆成功！");

                j.setObj(user);
                if (CodeConstant.SUPER_USER_LOGIN_NAME.equals(u.getLoginName())) {
                    LogUtil.adminLogs("管理员登录成功", "登录", request);
                } else {
                    LogUtil.userLogs("普通用户登录成功", "登录", request);
                }
            }
        } else {
            j.setMsg("登录名或密码错误！");
        }

        return j;
    }

    /**
     * 用户注册
     * 
     * @param user
     *            用户对象
     * @return
     */
    @ResponseBody
    @RequestMapping("/reg")
    public JsonResult reg(AdeUser user) {
        JsonResult j = new JsonResult();
        try {
            userService.reg(user);
            j.setSuccess(true);
            j.setMsg("注册成功！新注册的用户没有任何权限，请让管理员赋予权限后再使用本系统！");
            j.setObj(user);
        } catch (Exception e) {
            j.setMsg(e.getMessage());
        }
        return j;
    }

    /**
     * 退出登录
     * 
     * @param session
     * @return
     */
    @ResponseBody
    @RequestMapping("/logout")
    public JsonResult logout(HttpSession session) {
        JsonResult j = new JsonResult();
        if (session != null) {
            session.invalidate();
        }
        j.setSuccess(true);
        j.setMsg("注销成功！");
        return j;
    }

    /**
     * 跳转到用户管理页面
     * 
     * @return
     */
    @RequestMapping("/manager")
    public String manager() {
        return "/admin/user/user";
    }

    /**
     * 获取用户数据表格
     * 
     * @param user
     * @return
     */
    @RequestMapping("/dataGrid")
    @ResponseBody
    public EasyUIDataGrid dataGrid(AdeUser user, PageHelper ph) {
        return userService.dataGrid(user, ph);
    }

    /**
     * 跳转到添加用户页面
     * 
     * @param request
     * @return
     */
    @RequestMapping("/addPage")
    public String addPage(HttpServletRequest request) {
        AdeUser u = new AdeUser();
        u.setId(StringUtil.generateUUID());
        request.setAttribute("user", u);
        request.setAttribute("operate", CodeConstant.OPERATE_ADD);
        return "/admin/user/userEdit";
    }

    /**
     * 添加用户
     * 
     * @return
     */
    @RequestMapping("/add")
    @ResponseBody
    public JsonResult add(AdeUser user) {
        JsonResult j = new JsonResult();
        try {
            userService.add(user);
            j.setSuccess(true);
            j.setMsg("添加成功！");
            j.setObj(user);
        } catch (Exception e) {
            j.setMsg(e.getMessage());
        }
        return j;
    }

    /**
     * 跳转到用户修改页面
     * 
     * @return
     */
    @RequestMapping("/editPage")
    public String editPage(HttpServletRequest request, String id) {
        AdeUser u = userService.get(id);
        request.setAttribute("user", u);
        request.setAttribute("operate", CodeConstant.OPERATE_EDIT);
        return "/admin/user/userEdit";
    }

    /**
     * 修改用户
     * 
     * @param user
     * @return
     */
    @RequestMapping("/edit")
    @ResponseBody
    public JsonResult edit(AdeUser user) {
        JsonResult j = new JsonResult();
        try {
            userService.edit(user);
            j.setSuccess(true);
            j.setMsg("编辑成功！");
            j.setObj(user);
        } catch (Exception e) {
            j.setMsg(e.getMessage());
        }
        return j;
    }

    /**
     * 删除用户
     * 
     * @param id
     * @return
     */
    @RequestMapping("/delete")
    @ResponseBody
    public JsonResult delete(String id, HttpServletRequest request) {

        AdeUser user = UserUtil.getLoginUser(request);

        JsonResult j = new JsonResult();
        if (id != null && !id.equalsIgnoreCase(user.getId())) {// 不能删除自己
            userService.delete(id);
        }

        j.setMsg("停用成功！");
        j.setSuccess(true);
        return j;
    }

    /**
     * 恢复用户
     * 
     * @param id
     * @return
     */
    @RequestMapping("/recovery")
    @ResponseBody
    public JsonResult recovery(String id, HttpServletRequest request) {

        JsonResult j = new JsonResult();
        if (id != null) {
            userService.recovery(id);
        }
        j.setMsg("启用成功！");
        j.setSuccess(true);
        return j;
    }

    /**
     * 批量删除用户
     * 
     * @param ids
     *            ('0','1','2')
     * @return
     */
    @RequestMapping("/batchDelete")
    @ResponseBody
    public JsonResult batchDelete(String ids, HttpServletRequest request) {

        JsonResult j = new JsonResult();
        if (ids != null && ids.length() > 0) {
            for (String id : ids.split(",")) {
                if (id != null) {
                    this.delete(id, request);
                }
            }
        }
        j.setMsg("批量停用成功！");
        j.setSuccess(true);
        return j;
    }

    /**
     * 跳转到用户授权页面
     * 
     * @return
     */
    @RequestMapping("/grantPage")
    public String grantPage(String ids, HttpServletRequest request) {
        request.setAttribute("ids", ids);
        if (ids != null && !ids.equalsIgnoreCase("") && ids.indexOf(",") == -1) {
            AdeUser u = userService.get(ids);
            request.setAttribute("user", u);
        }
        return "/admin/user/userGrant";
    }

    /**
     * 用户授权
     * 
     * @param ids
     * @return
     */
    @RequestMapping("/grant")
    @ResponseBody
    public JsonResult grant(String userId, String roleIds) {
        JsonResult j = new JsonResult();
        userService.grant(userId, roleIds);
        j.setSuccess(true);
        j.setMsg("授权成功！");
        return j;
    }

    /**
     * 跳转到编辑用户密码页面
     * 
     * @param id
     * @param request
     * @return
     */
    @RequestMapping("/editPwdPage")
    public String editPwdPage(String id, HttpServletRequest request) {
        AdeUser u = userService.get(id);
        request.setAttribute("user", u);
        return "/admin/user/userEditPwd";
    }

    /**
     * 编辑用户密码
     * 
     * @param user
     * @return
     */
    @RequestMapping("/editPwd")
    @ResponseBody
    public JsonResult editPwd(AdeUser user) {
        JsonResult j = new JsonResult();
        userService.editPwd(user);
        j.setSuccess(true);
        j.setMsg("编辑成功！");
        return j;
    }

    /**
     * 跳转到编辑自己的密码页面
     * 
     * @return
     */
    @RequestMapping("/editMyselfPwdPage")
    public String editMyselfPwdPage() {
        return "/admin/user/editMyselfPwd";
    }

    /**
     * 修改自己的密码
     * 
     * @param session
     * @param pwd
     * @return
     */
    @RequestMapping("/editCurrentUserPwd")
    @ResponseBody
    public JsonResult editCurrentUserPwd(HttpServletRequest request, String id, String oldPwd, String pwd) {

        JsonResult j = new JsonResult();
        AdeUser user = UserUtil.getLoginUser(request);
        if (user != null) {
            id = user.getId();
            if (userService.editCurrentUserPwd(id, oldPwd, pwd)) {
                j.setSuccess(true);
                j.setMsg("编辑密码成功，下次登录生效！");
            } else {
                j.setMsg("原密码错误！");
            }
        } else {
            j.setMsg("登录超时，请重新登录！");
        }
        return j;
    }

    /**
     * 跳转到显示用户角色页面
     * 
     * @return
     */
    @RequestMapping("/currentUserRolePage")
    public String currentUserRolePage(HttpServletRequest request) {
        AdeUser user = UserUtil.getLoginUser(request);
        request.setAttribute("userRoles", JacksonUtil.toJSONString(roleService.tree(user)));
        return "/admin/user/userRole";
    }

    /**
     * 跳转到显示用户权限页面
     * 
     * @return
     */
    @RequestMapping("/currentUserResourcePage")
    public String currentUserResourcePage(HttpServletRequest request) {
        AdeUser user = UserUtil.getLoginUser(request);
        request.setAttribute("userResources", JacksonUtil.toJSONString(moduleService.treeAllType(user)));
        return "/admin/user/userResource";
    }

    /**
     * 获取数据字典列表
     * 
     * @param navigation
     * @param request
     * @return
     */
    @ResponseBody
    @RequestMapping("/userComboTree")
    public List<EasyUIComboTree> getUser() {
        return userService.getuser();
    }

    /**
     * 跳转导入页面
     * 
     * @return
     */
    @RequestMapping("/importPage")
    public String importPage() {
        return "/admin/user/importPage";
    }

    @RequestMapping("/importInfo")
    @ResponseBody
    public JsonResult importInfo(HttpServletRequest request, HttpServletResponse response)
            throws JsonGenerationException, JsonMappingException, IOException {
        JsonResult j = new JsonResult();
        // 转型为MultipartHttpRequest：
        MultipartHttpServletRequest multipartRequest = (MultipartHttpServletRequest) request;
        // 获得文件：
        MultipartFile btnFile = multipartRequest.getFile("btnFile");

        ObjectMapper obj = new ObjectMapper();
        String realPath = request.getSession().getServletContext().getRealPath("/excelInfo/");

        // 文件路径
        File dirPath = new File(realPath);
        if (!dirPath.exists()) {
            dirPath.mkdir();
        }
        // 设置编码方式
        response.setContentType("text/plain; charset=UTF-8");
        String myfileName = null;

        if (btnFile.isEmpty()) {
            // obj.writeValue(response.getOutputStream(), "选择文件");
            j.setMsg("请选择文件");
            return j;
        } else {
            myfileName = btnFile.getOriginalFilename();// 获取原始文件名称

            String fileExt = myfileName.substring(myfileName.lastIndexOf(".") + 1).toLowerCase();
            if (!"xlsx".equals(fileExt)) {
                j.setMsg("上传文件扩展名是不允许的扩展名。\n只允许xlsx格式。");
                return j;
            }
            String editName = StringUtil.generateUUID() + myfileName.substring(myfileName.lastIndexOf("."));// 避免重复
            try {
                File excelFile = new File(realPath, editName);
                FileUtils.copyInputStreamToFile(btnFile.getInputStream(), excelFile);
                userService.saveExcelInfo(excelFile);
                j.setSuccess(true);
                j.setMsg("导入成功！");

            } catch (Exception e) {
                // obj.writeValue(response.getOutputStream(), "文件上传失败，IO异常！");
                j.setMsg("上传文件上传失败!!!");
                return j;
            }
        }
        obj.writeValue(response.getOutputStream(), j);
        return j;
    }
}
